package net.stuffrepos.bricknetcenter.plugins.bricklink;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import net.stuffrepos.bricknetcenter.database.DataManager;
import net.stuffrepos.bricknetcenter.database.DataManager.InformationManager.InformationNode;
import net.stuffrepos.bricknetcenter.database.schema.Information;
import net.stuffrepos.bricknetcenter.http.HttpRequest;
import net.stuffrepos.bricknetcenter.provider.HttpProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class BrickLinkHttpProvider implements HttpProvider {

    private static final Log log = LogFactory.getLog(BrickLinkHttpProvider.class);
    private static final String PROVIDER_NAME = "www.bricklink.com";
    private static final Map<String, Information.Type> tagToInformationType;
    private static final Set<String> tagIgnored;

    static {
        tagToInformationType = new HashMap<String, Information.Type>();
        tagToInformationType.put("ITEMNAME", Information.Type.Name);
        tagToInformationType.put("CATEGORY", Information.Type.Category);
        tagToInformationType.put("ITEMYEAR", Information.Type.Year);
        tagToInformationType.put("ITEMWEIGHT", Information.Type.Weight);
        tagToInformationType.put("ITEMDIMX", Information.Type.DimensionX);
        tagToInformationType.put("ITEMDIMY", Information.Type.DimensionY);
        tagToInformationType.put("ITEMDIMZ", Information.Type.DimensionZ);

        tagIgnored = new TreeSet<String>();
        tagIgnored.add("ITEMTYPE");
        tagIgnored.add("ITEMID");
    }

    @Override
    public Collection<HttpRequest> getRootRequests() {
        List<HttpRequest> list = new LinkedList<HttpRequest>();
        list.add(new BrickLinkItemTypesRequest());
        for (BrickLinkItemType itemType : BrickLinkItemType.values()) {
            if (itemType.isCatalogued()) {
                list.add(new BrickLinkItemCatalogItemsRequest(itemType));
            }
        }
        return list;
    }

    @Override
    public String getName() {
        return PROVIDER_NAME;
    }

    public static InformationNode getProviderNode() throws Exception {
        return DataManager.getInstance().getInformationManager().getInformationNode(
                Information.Type.Provider,
                PROVIDER_NAME);
    }

    public static Information.Type getInformationTypeByTagName(String tagName) {
        if (tagToInformationType.containsKey(tagName)) {
            return tagToInformationType.get(tagName);
        } else if (tagIgnored.contains(tagName)) {
            return null;
        } else {
            throw new RuntimeException("No information type associated with tag name \"" + tagName + "\" was found");
        }
    }
}
